package com.ruoyi.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.enums.*;
import com.ruoyi.business.mapper.TRegisterInfoMapper;
import com.ruoyi.business.payment.enums.OrderRefundStatus;
import com.ruoyi.business.payment.enums.PaymentOrderStatus;
import com.ruoyi.business.payment.service.ITRegisterPaymentOrderService;
import com.ruoyi.business.payment.vo.TRegisterPaymentOrderDto;
import com.ruoyi.business.service.*;
import com.ruoyi.business.utils.BusinessUtils;
import com.ruoyi.business.vo.*;
import com.ruoyi.business.vo.export.ExportRegisterInfoVo;
import com.ruoyi.business.vo.export.ExportSignedFilesVo;
import com.ruoyi.business.vo.export.RegisterManualAllInfoVo;
import com.ruoyi.business.vo.export.RegisterManualInfoVo;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.RoleConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 报名信息Service业务层处理
 *
 * @author Tellsea
 * @date 2024-01-24
 */
@Service
@RequiredArgsConstructor
public class TRegisterInfoServiceImpl extends ServiceImpl<TRegisterInfoMapper, TRegisterInfo> implements ITRegisterInfoService {

    private final ITRegisterLearnService registerLearnService;
    private final ITRegisterWorkService registerWorkService;
    private final ITRegisterLanguageService registerLanguageService;
    private final ITRegisterDeptService registerDeptService;
    private final ITRegisterTypeService registerTypeService;
    private final ITAuditLogService auditLogService;
    private final ITRegisterNoticeService registerNoticeService;
    private final ITRegisterAllocationService registerAllocationService;
    private final ITRegisterLeaveService registerLeaveService;
    private final ITRegisterManualService registerManualService;
    private final ISysUserService sysUserService;
    private final ISysUserRoleService sysUserRoleService;
    private final RedisCache redisCache;
    private final ITCooperateInfoService cooperateInfoService;
    private final ITResourceProgressService resourceProgressService;
    private final ITSureInfoService itSureInfoService;

    private final ITUserOptLogService tUserOptLogService;

    private final ITRegisterSignService registerSignService;
    private final ITRegisterPaymentOrderService tRegisterPaymentOrderService;


    private Page<TRegisterInfoVo> handleResult(Page<TRegisterInfoVo> page) {
        page.getRecords().forEach(e -> handleResult(e));
        return page;
    }

    private List<TRegisterInfoVo> handleResult(List<TRegisterInfoVo> list) {
        list.forEach(e -> handleResult(e));
        return list;
    }

    private TRegisterInfoVo handleResult(TRegisterInfoVo vo) {
        if (ObjectUtil.isNull(vo)) {
            return null;
        }
        if (ObjectUtil.isNotNull(vo.getRegisterDeptId())) {
            TRegisterDept registerDept = registerDeptService.getById(vo.getRegisterDeptId());
            if (ObjectUtil.isNotEmpty(registerDept)) {
                TRegisterType registerType = registerTypeService.getById(registerDept.getRegisterDeptType());
                if (ObjectUtil.isNotEmpty(registerType)) {
                    vo.setRegisterTypeName(registerType.getRegisterTypeName());
                }
            }
        }
        if (ObjectUtil.isNotEmpty(vo.getScoreLevelUserId())) {
            SysUser sysUser = sysUserService.getById(vo.getScoreLevelUserId());
            vo.setScoreLevelUserName(sysUser.getUserName());
            vo.setScoreLevelNickName(sysUser.getNickName());
        }else{
            TRegisterDeptVo tRegisterDeptVo = registerDeptService.queryById(vo.getRegisterDeptId());
            if(tRegisterDeptVo!=null){
                SysUser sysUser = sysUserService.getById(tRegisterDeptVo.getSecretaryUserId());
                vo.setScoreLevelUserName(sysUser.getUserName());
                vo.setScoreLevelNickName(sysUser.getNickName());
            }
        }
        vo.setAuditStatusName(AuditStatusEnums.getNameByCode(vo.getAuditStatus()));
        vo.setNoticeStatusName(NoticeStatusEnums.getNameByCode(vo.getNoticeStatus()));
        vo.setSureStatusName(SureStatusEnums.getNameByCode(vo.getSureStatus()));
        vo.setAllocationStatusName(AllocationStatusEnums.getNameByCode(vo.getAllocationStatus()));
        vo.setCultureStatusName(CultureStatusEnums.getNameByCode(vo.getCultureStatus()));
        vo.setLeaveStatusName(LeaveStatusEnums.getNameByCode(vo.getLeaveStatus()));
        vo.setCurrentStatusName(CurrentStatusEnums.getNameByCode(vo.getCurrentStatus()));
        vo.setGraduationStatusName(GraduationStatusEnums.getNameByCode(vo.getGraduationStatus()));
        vo.setGraduationAuditStatusName(GraduationAuditStatusEnums.getNameByCode(vo.getGraduationAuditStatus()));
        vo.setEvaluateStatusName(EvaluateStatusEnums.getNameByCode(vo.getEvaluateStatus()));
        vo.setPayStatusName(PayStatusEnums.getNameByCode(vo.getPayStatus()));
        vo.setRegisterLearnVoList(registerLearnService.queryAll((TRegisterLearnVo) new TRegisterLearnVo().setRegisterId(vo.getId())));
        vo.setRegisterWorkVoList(registerWorkService.queryAll((TRegisterWorkVo) new TRegisterWorkVo().setRegisterId(vo.getId())));
        vo.setRegisterLanguageVoList(registerLanguageService.queryAll((TRegisterLanguageVo) new TRegisterLanguageVo().setRegisterId(vo.getId())));
        List<TAuditLogVo> tAuditLogList = auditLogService.queryAll((TAuditLogVo) new TAuditLogVo().setRegisterId(vo.getId()));
        vo.setAuditLogVoList(tAuditLogList);
        if(tAuditLogList!=null && !tAuditLogList.isEmpty() && vo.getAuditStatus().equals(AuditStatusEnums.NO.getCode())){
            TAuditLogVo auditLogVoHis = tAuditLogList.get(0);
            // 如果最近一条数据是管理员退回的，那么查询的结果就是管理员审批
            if(auditLogVoHis.getAuditStatus()==2L && auditLogVoHis.getAuditUserId()==1L){
                vo.setAuditStatus(AuditStatusEnums.WAIT.getCode());
            }
        }
        TRegisterNoticeVo registerNoticeVo = registerNoticeService.queryByRegisterId(vo.getId());
        if (ObjectUtil.isNotEmpty(registerNoticeVo)) {
            vo.setRegisterNoticeVo(registerNoticeVo);
            vo.setJobNumber(registerNoticeVo.getJobNumber());
            vo.setDurationMoney(String.valueOf(registerNoticeVo.getEngageMoney()));
            DateTime endDate = DateUtil.parse(registerNoticeVo.getEndDate(), "yyyy/MM/dd");
            DateTime endDftDate = DateUtil.parse(registerNoticeVo.getEndDateDefault(), "yyyy/MM/dd");
            long diff = Math.abs(endDate.getTime() - endDftDate.getTime());
            long daysBetween = diff / (24 * 60 * 60 * 1000);
            if(daysBetween>0){
                vo.setLeaveStatusDesc("延后"+daysBetween+"天");
            }
        }
        //获取模板内容
        if(itSureInfoService.list() !=null && !itSureInfoService.list().isEmpty()){
            TSureInfo tSureInfo = itSureInfoService.list().get(0);
            vo.setTSureInfo(tSureInfo);
        }
        vo.setRegisterAllocationVoList(registerAllocationService.queryAll((TRegisterAllocationVo) new TRegisterAllocationVo().setRegisterId(vo.getId())));
        vo.setRegisterLeaveVoList(registerLeaveService.queryAll((TRegisterLeaveVo) new TRegisterLeaveVo().setRegisterId(vo.getId())));
        vo.setRegisterManualVo(registerManualService.queryByRegisterId(vo.getId()));
        vo.setProgress(resourceProgressService.getProgress(vo.getUserId()));
        vo.setOptLogVoList(tUserOptLogService.queryById(vo.getId().toString()));

        vo.setRegisterFlowList(this.getFlow(vo.getId()));

        this.handleWorkFlow(vo);
        return vo;
    }

    @Override
    public TableDataInfo<TRegisterInfoVo> queryList(TRegisterInfoVo entity) {
        if (StrUtil.isNotEmpty(entity.getQrCode()) && StrUtil.isNotEmpty(entity.getQrCodeKey())) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(entity.getQrCodeKey(), "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                throw new ServiceException("验证码错误");
            }
        }
        handleAuthRegister(entity);
        Page<TRegisterInfoVo> page = this.baseMapper.queryList(PageUtils.buildPage(), entity);
        List<TRegisterInfoVo> records = page.getRecords();
        // 获取请假数据
        List<Long> registerIdList = records.stream().map(TRegisterInfoVo::getId).collect(Collectors.toList());
        List<TRegisterLeaveStatVo> registerLeaveStat = registerLeaveService.getRegisterLeaveStat(registerIdList);
        Map<Long, TRegisterLeaveStatVo> leaveStatVoMap = registerLeaveStat.stream().collect(Collectors.toMap(TRegisterLeaveStatVo::getRegisterId, Function.identity(),
                (existing, replacement) -> existing));
        for (TRegisterInfoVo recordItem : records) {
            TRegisterLeaveStatVo tRegisterLeaveStatVo = leaveStatVoMap.get(recordItem.getId());
            recordItem.setLeaveStat(tRegisterLeaveStatVo);
        }
        return PageUtils.buildDataInfo(handleResult(page));
    }

    @Override
    public TableDataInfo<TRegisterInfoVo> queryListByStudent(TRegisterInfoVo entity) {
        if (StrUtil.isNotEmpty(entity.getQrCode()) && StrUtil.isNotEmpty(entity.getQrCodeKey())) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(entity.getQrCodeKey(), "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                throw new ServiceException("验证码错误");
            }
        }
        Page<TRegisterInfoVo> page = this.baseMapper.queryList(PageUtils.buildPage(), entity);
        return PageUtils.buildDataInfo(handleResult(page));
    }

    @Override
    public TableDataInfo<TRegisterInfoVo> queryIndexList(TRegisterInfoVo entity) {
        if (StrUtil.isNotEmpty(entity.getQrCode()) && StrUtil.isNotEmpty(entity.getQrCodeKey())) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(entity.getQrCodeKey(), "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                throw new ServiceException("验证码错误");
            }
        }
        handleAuthRegister(entity);
        Page<TRegisterInfoVo> page = this.baseMapper.queryIndexList(PageUtils.buildPage(), entity);
        return PageUtils.buildDataInfo(handleResult(page));
    }
    @Override
    public TableDataInfo<TRegisterInfoVo> queryIndexListNoDetail(TRegisterInfoVo entity) {
        if (StrUtil.isNotEmpty(entity.getQrCode()) && StrUtil.isNotEmpty(entity.getQrCodeKey())) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(entity.getQrCodeKey(), "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                throw new ServiceException("验证码错误");
            }
        }
        handleAuthRegister(entity);
        Page<?> pageParams = new Page<>(1,1);
        Page<TRegisterInfoVo> page = this.baseMapper.queryIndexList(pageParams, entity);
        return PageUtils.buildDataInfo(page);
    }


    @Override
    public List<TRegisterInfoVo> queryAll(TRegisterInfoVo entity) {
        if (!BooleanUtil.isTrue(entity.getNoAuth())) {
            handleAuthRegister(entity);
        }
        List<TRegisterInfoVo> list = this.baseMapper.queryList(entity);
        return handleResult(list);
    }

    @Override
    public List<TRegisterInfoVo> queryAllSingle(TRegisterInfoVo entity) {
        if (!BooleanUtil.isTrue(entity.getNoAuth())) {
            handleAuthRegister(entity);
        }
        List<TRegisterInfoVo> list = this.baseMapper.queryList(entity);
        List<Long> idList = new ArrayList<>();
        for (TRegisterInfoVo vo : list) {
            idList.add(vo.getId());
        }
        TRegisterNoticeVo registerNotice = new TRegisterNoticeVo();
        registerNotice.setRegisterIdList(idList);
        List<TRegisterNoticeVo> noticeDataList = registerNoticeService.queryAll(registerNotice);
        Map<Long, List<TRegisterNoticeVo>> mapCache = noticeDataList.stream().collect(Collectors.groupingBy(TRegisterNoticeVo::getRegisterId));
        for (TRegisterInfoVo vo : list) {
            List<TRegisterNoticeVo> registerNoticeVoList = mapCache.get(vo.getId());
            if (ObjectUtil.isNotEmpty(registerNoticeVoList) && !registerNoticeVoList.isEmpty()) {
                registerNoticeVoList.sort(Comparator.comparing(TRegisterNoticeVo::getCreateTime).reversed());
                TRegisterNoticeVo registerNoticeVo = registerNoticeVoList.get(0);
                vo.setRegisterNoticeVo(registerNoticeVo);
                vo.setJobNumber(registerNoticeVo.getJobNumber());
                vo.setDurationMoney(String.valueOf(registerNoticeVo.getEngageMoney()));
            }
        }
        return list;
    }

    @Override
    public TRegisterBaseVo queryByCount(TRegisterBaseVo entity) {
        handleAuthBase(entity);
        return this.baseMapper.queryByCount(entity);
    }

    @Override
    public TableDataInfo<TRegisterBaseVo> queryByDept(TRegisterBaseVo entity) {
        handleAuthBase(entity);
        return PageUtils.buildDataInfo(this.baseMapper.queryByDept(PageUtils.buildPage(), entity));
    }

    private void handleAuthRegister(TRegisterInfoVo entity) {
//        if (SecurityUtils.hasRole(RoleConstants.SECRETARY.getRoleKey())
//                && entity.getIsAllocationTeachModule()!=null
//                && entity.getIsAllocationTeachModule()) {
//            // 进修秘书放权
//            entity.setUserId(null);
//           return;
//        }
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        if (SecurityUtils.hasRole(RoleConstants.SECRETARY.getRoleKey())
                || SecurityUtils.hasRole(RoleConstants.DEPT_MANAGE.getRoleKey())) {
            List<TRegisterDept> deptList = registerDeptService.lambdaQuery()
                    .eq(TRegisterDept::getManageUserId, userId)
                    .or()
                    .eq(TRegisterDept::getSecretaryUserId, userId)
                    .list();
            entity.setRegisterDeptIdList(deptList.stream().map(TRegisterDept::getId).collect(Collectors.toList()));
        } else if (SecurityUtils.hasRole(RoleConstants.TEACHER.getRoleKey())) {
            entity.setTeacherUserId(String.valueOf(userId));
        } else if (SecurityUtils.hasRole(RoleConstants.STUDENT.getRoleKey())) {
            entity.setUserId(userId);
        }
    }

    private void handleAuthBase(TRegisterBaseVo entity) {
//        if (SecurityUtils.hasRole(RoleConstants.SECRETARY.getRoleKey())
//                && entity.getIsAllocationTeachModule()!=null
//                && entity.getIsAllocationTeachModule()) {
//            // 进修秘书放权
//            entity.setUserId(null);
//            return;
//        }
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        if (SecurityUtils.hasRole(RoleConstants.SECRETARY.getRoleKey())
                || SecurityUtils.hasRole(RoleConstants.DEPT_MANAGE.getRoleKey())) {
            List<TRegisterDept> deptList = registerDeptService.lambdaQuery()
                    .eq(TRegisterDept::getManageUserId, userId)
                    .or()
                    .eq(TRegisterDept::getSecretaryUserId, userId)
                    .list();
            entity.setRegisterDeptIdList(deptList.stream().map(TRegisterDept::getId).collect(Collectors.toList()));
        } else if (SecurityUtils.hasRole(RoleConstants.TEACHER.getRoleKey())) {
            entity.setTeacherUserId(String.valueOf(userId));
        }
    }

    @Override
    public TRegisterInfoVo queryById(Long id) {
        TRegisterInfoVo registerInfoVo = this.baseMapper.queryById(id);
        // 获取请假数据
        List<Long> registerIdList = Collections.singletonList(id);
        List<TRegisterLeaveStatVo> registerLeaveStat = registerLeaveService.getRegisterLeaveStat(registerIdList);
        Map<Long, TRegisterLeaveStatVo> leaveStatVoMap = registerLeaveStat.stream().collect(Collectors.toMap(TRegisterLeaveStatVo::getRegisterId, Function.identity(),
                (existing, replacement) -> existing));
        TRegisterLeaveStatVo tRegisterLeaveStatVo = leaveStatVoMap.get(id);
        registerInfoVo.setLeaveStat(tRegisterLeaveStatVo);

        return handleResult(registerInfoVo);
    }

    @Override
    public List<FlowNodeVo> getFlow(Long id) {
        List<FlowNodeVo> result = new ArrayList<>();
        TRegisterInfoVo registerInfoVo = this.baseMapper.queryById(id);
        // 进修申请状态
        FlowNodeVo registerStatus = new FlowNodeVo();
        registerStatus.setNodeName("进修申请状态");
        registerStatus.setNodeOrder(1);
        if(registerInfoVo.getAuditStatus() ==null || registerInfoVo.getAuditStatus()==0L){
            registerStatus.setNodeStatus(0L);
            registerStatus.setNodeStatusDesc("暂存");
            registerStatus.setFinish(false);
        }else{
            registerStatus.setNodeStatus(1L);
            registerStatus.setNodeStatusDesc("已提交进修申请");
            registerStatus.setFinish(true);
        }
        registerStatus.setCanClick(true);
        result.add(registerStatus);
        // 审批状态
        FlowNodeVo auditStatus = new FlowNodeVo();
        auditStatus.setNodeName("进修医院资质审核");
        auditStatus.setNodeOrder(2);
        auditStatus.setNodeStatus(registerInfoVo.getAuditStatus());
        auditStatus.setNodeStatusDesc(AuditStatusEnums.getNameByCode(registerInfoVo.getAuditStatus()));
        auditStatus.setFinish(Objects.equals(registerInfoVo.getAuditStatus(), AuditStatusEnums.SUCCESS.getCode())
                || Objects.equals(registerInfoVo.getAuditStatus(), AuditStatusEnums.FAIL.getCode())
                || Objects.equals(registerInfoVo.getAuditStatus(), AuditStatusEnums.RETURNED.getCode()));
        auditStatus.setCanClick(registerStatus.getNodeStatus() == 1L);
        result.add(auditStatus);
        if(Objects.equals(registerInfoVo.getAuditStatus(), AuditStatusEnums.FAIL.getCode())){
            // 审批拒绝中断后续
            return result;
        }
        // 通知书状态
        FlowNodeVo noticeStatus = new FlowNodeVo();
        noticeStatus.setNodeName("进修医院发放通知书");
        noticeStatus.setNodeOrder(3);
        if(registerInfoVo.getNoticeStatus()==null || registerInfoVo.getNoticeStatus()==0 || registerInfoVo.getNoticeStatus()==1){
            noticeStatus.setNodeStatus(registerInfoVo.getNoticeStatus());
            noticeStatus.setNodeStatusDesc("待发通知");
            noticeStatus.setFinish(false);
        }else{
            noticeStatus.setNodeStatus(registerInfoVo.getNoticeStatus());
            noticeStatus.setNodeStatusDesc("已发通知");
            noticeStatus.setFinish(true);
        }
        noticeStatus.setCanClick(Objects.equals(auditStatus.getNodeStatus(), AuditStatusEnums.SUCCESS.getCode()));
        result.add(noticeStatus);

        // 报道状态
        FlowNodeVo sureStatus = new FlowNodeVo();
        sureStatus.setNodeName("确定按时报到");
        sureStatus.setNodeOrder(4);
        sureStatus.setNodeStatus(registerInfoVo.getNoticeStatus());
        sureStatus.setNodeStatusDesc(NoticeStatusEnums.getNameByCode(registerInfoVo.getNoticeStatus()));
        sureStatus.setFinish(Objects.equals(registerInfoVo.getNoticeStatus(), NoticeStatusEnums.SUCCESS.getCode())
                || Objects.equals(registerInfoVo.getNoticeStatus(), NoticeStatusEnums.CANCEL.getCode()));
        sureStatus.setCanClick(noticeStatus.isFinish());
        if(registerInfoVo.getNoticeStatus()==null
                || registerInfoVo.getNoticeStatus()==0){
            sureStatus.setNodeStatusDesc("待确定");
        }
        result.add(sureStatus);
        if(Objects.equals(registerInfoVo.getNoticeStatus(), NoticeStatusEnums.CANCEL.getCode())
               || Objects.equals(registerInfoVo.getNoticeStatus(), NoticeStatusEnums.DELAYED.getCode())){
            // 通知书取消，延期未确认，后续中断
            return result;
        }
        // 支付状态
        FlowNodeVo payStatus = new FlowNodeVo();
        payStatus.setNodeName("支付进修费用");
        payStatus.setNodeOrder(5);
        payStatus.setNodeStatusDesc("待支付");
        TRegisterPaymentOrderDto paymentOrderDto = tRegisterPaymentOrderService.queryByRegisterId(id);
        if(paymentOrderDto!=null){
            payStatus.setNodeStatus(Long.valueOf(paymentOrderDto.getPaymentStatus()));
            payStatus.setNodeStatusDesc(PaymentOrderStatus.getNameByCode(paymentOrderDto.getPaymentStatus()));
            if(paymentOrderDto.getRefundStatus()!=null){
                payStatus.setRefundStatus(paymentOrderDto.getRefundStatus());
                payStatus.setNodeStatusDesc(OrderRefundStatus.getNameByCode(paymentOrderDto.getRefundStatus()));
            }
        }
        if(registerInfoVo.getPayStatus()==null || registerInfoVo.getPayStatus()==0 || registerInfoVo.getPayStatus()==1){
            payStatus.setFinish(false);
        }else{
            payStatus.setFinish(true);
        }
        result.add(payStatus);
        // 进修退款成功后，后面的所有流程中断，不显示，只显示到【已退款】这步。
        if(Objects.equals(registerInfoVo.getPayStatus(), PayStatusEnums.REFUND.getCode())){
            return result;
        }
        // 终止进修的后面的也不显示
        if(Objects.equals(registerInfoVo.getGraduationStatus(), GraduationStatusEnums.STOP.getCode())){
            return result;
        }
        // 岗前视频培训
        FlowNodeVo videoStudyStatus = new FlowNodeVo();
        videoStudyStatus.setNodeName("完成岗前培训视频");
        videoStudyStatus.setNodeOrder(6);
        BigDecimal progress = resourceProgressService.getProgress(registerInfoVo.getUserId());
        if(progress.compareTo(new BigDecimal("100.00"))==0){
            videoStudyStatus.setNodeStatus(1L);
            videoStudyStatus.setFinish(true);
        }else{
            videoStudyStatus.setNodeStatus(0L);
            videoStudyStatus.setFinish(false);
        }
        videoStudyStatus.setNodeStatusDesc("进度:"+String.format("%.0f",progress.doubleValue())+"%");
        result.add(videoStudyStatus);

        TRegisterSignVo signVo = new TRegisterSignVo();
        signVo.setRegisterId(id);
        signVo.setDeleteStatus(1L);
        List<TRegisterSignVo> registerSignVoList = registerSignService.queryAll(signVo);
        FlowNodeVo jxsgzsStatus = new FlowNodeVo();
        FlowNodeVo lcywryStatus = new FlowNodeVo();
        FlowNodeVo xfcnsStatus = new FlowNodeVo();
        if(registerSignVoList==null || registerSignVoList.isEmpty()){
            // 签署进修生告知书
            jxsgzsStatus.setNodeName("签署进修生告知书");
            jxsgzsStatus.setNodeOrder(7);
            jxsgzsStatus.setNodeStatus(0L);
            jxsgzsStatus.setNodeStatusDesc("去签署");
            jxsgzsStatus.setFinish(false);
            result.add(jxsgzsStatus);
            // 签署临床医务人员行风自律承诺书
            lcywryStatus.setNodeName("签署临床医务人员行风自律承诺书");
            lcywryStatus.setNodeOrder(8);
            lcywryStatus.setNodeStatus(0L);
            lcywryStatus.setNodeStatusDesc("去签署");
            lcywryStatus.setFinish(false);
            result.add(lcywryStatus);
            // 科主任签署行风承诺书
            xfcnsStatus.setNodeName("科主任签署行风承诺书");
            xfcnsStatus.setNodeOrder(9);
            xfcnsStatus.setNodeStatus(0L);
            xfcnsStatus.setNodeStatusDesc("未签署");
            xfcnsStatus.setFinish(false);
            result.add(xfcnsStatus);
        }else{
            // 签署进修生告知书
            boolean isSignJXSGZS = registerSignVoList.stream()
                    .anyMatch(item -> StringUtils.equals(item.getSignShort(), SignShortEnums.JXS_GZS.name())
                            && item.getDeleteStatus() == 1L && item.getSignSelfStatus() == 1L);
            if(isSignJXSGZS){
                jxsgzsStatus.setNodeName("签署进修生告知书");
                jxsgzsStatus.setNodeOrder(7);
                jxsgzsStatus.setNodeStatus(1L);
                jxsgzsStatus.setNodeStatusDesc("已签署");
                jxsgzsStatus.setFinish(true);
                result.add(jxsgzsStatus);
            }else{
                jxsgzsStatus.setNodeName("签署进修生告知书");
                jxsgzsStatus.setNodeOrder(7);
                jxsgzsStatus.setNodeStatus(0L);
                jxsgzsStatus.setNodeStatusDesc("去签署");
                jxsgzsStatus.setFinish(false);
                result.add(jxsgzsStatus);
            }

            // 签署临床医务人员行风自律承诺书
            // 科主任签署行风承诺书
//            String CNSType = registerInfoVo.getRegisterDeptId().equals(13L)?SignShortEnums.HS_CNS.name():SignShortEnums.KZR_CNS.name();
            List<TRegisterSignVo> signXFCNSList = registerSignVoList.stream()
                    .filter(item -> (StringUtils.equals(item.getSignShort(), SignShortEnums.HS_CNS.name()) || StringUtils.equals(item.getSignShort(), SignShortEnums.KZR_CNS.name()))
                            && item.getDeleteStatus() == 1L).collect(Collectors.toList());
            if(!signXFCNSList.isEmpty()){
                TRegisterSignVo signXFCNS = signXFCNSList.get(0);
                if(signXFCNS.getSignSelfStatus()==1){
                    lcywryStatus.setNodeName("签署临床医务人员行风自律承诺书");
                    lcywryStatus.setNodeOrder(8);
                    lcywryStatus.setNodeStatus(1L);
                    lcywryStatus.setNodeStatusDesc("已签署");
                    lcywryStatus.setFinish(true);
                    result.add(lcywryStatus);
                    if(signXFCNS.getSignOtherStatus()==1){
                        xfcnsStatus.setNodeName("科主任签署行风承诺书");
                        xfcnsStatus.setNodeOrder(9);
                        xfcnsStatus.setNodeStatus(1L);
                        xfcnsStatus.setNodeStatusDesc("已签署");
                        xfcnsStatus.setFinish(true);
                        result.add(xfcnsStatus);
                    }else{
                        xfcnsStatus.setNodeName("科主任签署行风承诺书");
                        xfcnsStatus.setNodeOrder(9);
                        xfcnsStatus.setNodeStatus(0L);
                        xfcnsStatus.setNodeStatusDesc("未签署");
                        xfcnsStatus.setFinish(false);
                        result.add(xfcnsStatus);
                    }

                } else {
                    lcywryStatus.setNodeName("签署临床医务人员行风自律承诺书");
                    lcywryStatus.setNodeOrder(8);
                    lcywryStatus.setNodeStatus(0L);
                    lcywryStatus.setNodeStatusDesc("去签署");
                    lcywryStatus.setFinish(false);
                    result.add(lcywryStatus);

                    xfcnsStatus.setNodeName("科主任签署行风承诺书");
                    xfcnsStatus.setNodeOrder(9);
                    xfcnsStatus.setNodeStatus(0L);
                    xfcnsStatus.setNodeStatusDesc("未签署");
                    xfcnsStatus.setFinish(false);
                    result.add(xfcnsStatus);
                }
            }else{
                lcywryStatus.setNodeName("签署临床医务人员行风自律承诺书");
                lcywryStatus.setNodeOrder(8);
                lcywryStatus.setNodeStatus(0L);
                lcywryStatus.setNodeStatusDesc("去签署");
                lcywryStatus.setFinish(false);
                result.add(lcywryStatus);

                xfcnsStatus.setNodeName("科主任签署行风承诺书");
                xfcnsStatus.setNodeOrder(9);
                xfcnsStatus.setNodeStatus(0L);
                xfcnsStatus.setNodeStatusDesc("未签署");
                xfcnsStatus.setFinish(false);
                result.add(xfcnsStatus);
            }
        }

        // 现场报到
        TRegisterNoticeVo registerNoticeVo = registerNoticeService.queryByRegisterId(id);
        FlowNodeVo sureDoneStatus = new FlowNodeVo();
        sureDoneStatus.setNodeName("现场报到(扫二维码)");
        sureDoneStatus.setNodeOrder(10);
        if(registerNoticeVo==null || registerNoticeVo.getSureTime()==null){
            sureDoneStatus.setNodeStatus(0L);
            sureDoneStatus.setNodeStatusDesc("待报到");
            sureDoneStatus.setFinish(false);
        }else{
            sureDoneStatus.setNodeStatus(1L);
            sureDoneStatus.setNodeStatusDesc("已报到");
            sureDoneStatus.setFinish(true);
        }
        result.add(sureDoneStatus);
        // 设置是否能点击操作，按照顺序
        // 当状态是待确认和延期未确认时，能点击
        payStatus.setCanClick(sureStatus.isFinish());
        videoStudyStatus.setCanClick(sureStatus.isFinish());
        jxsgzsStatus.setCanClick(sureStatus.isFinish());
        lcywryStatus.setCanClick(sureStatus.isFinish());
        xfcnsStatus.setCanClick(jxsgzsStatus.getNodeStatus()==1L && lcywryStatus.getNodeStatus()==1L);
        sureDoneStatus.setCanClick(sureStatus.isFinish());
        return result;
    }

    public void handleWorkFlow(TRegisterInfoVo vo){
        if(Objects.equals(vo.getPayStatus(), PayStatusEnums.REFUND.getCode())){
            // 进修退款成功后，我的进修：关于这笔进修的流程消失，不再显示
            vo.setWorkFlowList(Collections.emptyList());
            return;
        }
        List<WorkFlowNodeVo> flowNodeVoList = new ArrayList<>();
        WorkFlowNodeVo lcWorkTableNode = new WorkFlowNodeVo();
        lcWorkTableNode.setNodeOrder(1);
        lcWorkTableNode.setNodeName("填写临床工作表");
        lcWorkTableNode.setCanClick(true);
        lcWorkTableNode.setNodeStatus(0L);
        flowNodeVoList.add(lcWorkTableNode);

        WorkFlowNodeVo personalSummaryNode = new WorkFlowNodeVo();
        personalSummaryNode.setNodeOrder(2);
        personalSummaryNode.setNodeName("填写个人小结");
        personalSummaryNode.setCanClick(true);
        personalSummaryNode.setNodeStatus(0L);
        flowNodeVoList.add(personalSummaryNode);

        WorkFlowNodeVo workJudgeNode = new WorkFlowNodeVo();
        workJudgeNode.setNodeOrder(3);
        workJudgeNode.setNodeName("完成进修评价");
        workJudgeNode.setCanClick(true);
        workJudgeNode.setNodeStatus(0L);
        flowNodeVoList.add(workJudgeNode);

        WorkFlowNodeVo teacherScoreNode = new WorkFlowNodeVo();
        teacherScoreNode.setNodeOrder(4);
        teacherScoreNode.setNodeName("带教老师打分");
        teacherScoreNode.setCanClick(true);
        teacherScoreNode.setNodeStatus(0L);
        flowNodeVoList.add(teacherScoreNode);

        WorkFlowNodeVo studentLeaveNode = new WorkFlowNodeVo();
        studentLeaveNode.setNodeOrder(5);
        studentLeaveNode.setNodeName("进修医院确认考勤");
        studentLeaveNode.setCanClick(true);
        studentLeaveNode.setNodeStatus(0L);
        flowNodeVoList.add(studentLeaveNode);


        WorkFlowNodeVo graduationAuditNode = new WorkFlowNodeVo();
        graduationAuditNode.setNodeOrder(6);
        graduationAuditNode.setNodeName("结业申请");
        graduationAuditNode.setCanClick(true);
        graduationAuditNode.setNodeStatus(0L);
        flowNodeVoList.add(graduationAuditNode);

        // 学员报名id
        Long id = vo.getId();
        // 填写临床工作表+个人小结+进修评价
        TRegisterManualVo tRegisterManualVo = registerManualService.queryByRegisterId(id);
        List<String> lcWorkTableField = Arrays.asList("clinicNumber", "emergencyNumber", "averageNumber",
                "clinicEmergencyContent", "manageBeds", "caseNumber",
                "wardContent", "businessContent", "otherContent");
        if(BusinessUtils.areAnyFieldsNotFinish(tRegisterManualVo,lcWorkTableField)){
            lcWorkTableNode.setFinish(false);
            lcWorkTableNode.setNodeStatusDesc("未完成");
        }else{
            lcWorkTableNode.setFinish(true);
            lcWorkTableNode.setNodeStatus(1L);
            lcWorkTableNode.setNodeStatusDesc("已完成");
        }
        List<String> psuField = Collections.singletonList("personalSummary");
        if(BusinessUtils.areAnyFieldsNotFinish(tRegisterManualVo,psuField)){
            personalSummaryNode.setFinish(false);
            personalSummaryNode.setNodeStatusDesc("未完成");
        }else{
            personalSummaryNode.setNodeStatus(1L);
            personalSummaryNode.setFinish(true);
            personalSummaryNode.setNodeStatusDesc("已完成");
        }

        List<String> workJudgeField = Arrays.asList("introduceFlag", "planFlag", "environmentFlag",
                "teacherFlag", "businessFlag", "timecardFlag",
                "examineFlag", "strengthContent", "improveContent");
        if(BusinessUtils.areAnyFieldsNotFinish(tRegisterManualVo,workJudgeField)){
            workJudgeNode.setFinish(false);
            workJudgeNode.setNodeStatusDesc("未完成");
        }else{
            workJudgeNode.setNodeStatus(1L);
            workJudgeNode.setFinish(true);
            workJudgeNode.setNodeStatusDesc("已完成");
        }
        if(vo.getScoreLevel()==null || vo.getScoreTotal()==null){
            teacherScoreNode.setFinish(false);
            teacherScoreNode.setNodeStatusDesc("未完成");
        }else{
            teacherScoreNode.setNodeStatus(1L);
            teacherScoreNode.setFinish(true);
            teacherScoreNode.setNodeStatusDesc("已完成");
        }
        // 结业申请
        Long graduationAuditStatus = vo.getGraduationAuditStatus();
        if(Objects.equals(graduationAuditStatus, GraduationAuditStatusEnums.NULL.getCode())){
            graduationAuditNode.setNodeStatusDesc("提交申请");
            graduationAuditNode.setFinish(false);
        }
        if(Objects.equals(graduationAuditStatus, GraduationAuditStatusEnums.NO.getCode())
            || Objects.equals(graduationAuditStatus, GraduationAuditStatusEnums.WAIT.getCode())){
            graduationAuditNode.setNodeStatusDesc("待审核");
            graduationAuditNode.setFinish(false);
        }

        if(Objects.equals(graduationAuditStatus, GraduationAuditStatusEnums.SUCCESS.getCode())){
            graduationAuditNode.setNodeStatus(1L);
            graduationAuditNode.setNodeStatusDesc("已结业");
            graduationAuditNode.setFinish(true);
        }

        if(Objects.equals(graduationAuditStatus, GraduationAuditStatusEnums.FAIL.getCode())){
            graduationAuditNode.setNodeStatusDesc("已肆业");
            graduationAuditNode.setFinish(false);
        }

        vo.setWorkFlowList(flowNodeVoList);
    }

    @Override
    public AjaxResult saveBefore(TRegisterInfoVo entity) {
        checkRegister(entity);
        return AjaxResult.success("正常报名");
    }

    @Override
    public AjaxResult saveEntity(TRegisterInfoVo entity) {
        if (entity.getAgentUserId() == null){ //不是代理报名
            String batchDate = entity.getBatchDate();
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            try {
                String fh= batchDate.contains("-")?"-":"~";
                String[] split = batchDate.split(fh);
                Date startDate = format.parse(split[1]);
                // 如果是退回状态，结束日期加30天
                if(entity.getId()!=null){
                    TRegisterInfo oldRegisterInfo = getById(entity.getId());
                    if (AuditStatusEnums.RETURNED.getCode().equals(oldRegisterInfo.getAuditStatus())) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(startDate);
                        calendar.add(Calendar.DAY_OF_MONTH, 30); // 增加30天
                        startDate = calendar.getTime();
                    }
                }
                Date date = new Date();
                int compare = DateUtil.compare(date,startDate);
                if (compare >= 1){
                    return AjaxResult.error("当前进修期限已过，请删除后重新提交进行申请");
                }
            } catch (ParseException e) {
                log.error("进修开始时间格式解析异常,进行编号ID:"+entity.getId());
            }
        }
        Long curAuditStatus = entity.getAuditStatus();
        checkRegister(entity);
        List<TCooperateInfo> cooperateInfoList = cooperateInfoService.list();
        // 合作单位
        for (TCooperateInfo cooperateInfo : cooperateInfoList) {
            if (StrUtil.equals(entity.getUnitHospitalName(), cooperateInfo.getProjectName())) {
                String[] split = cooperateInfo.getCooperateTime().split("-");
                Date startTime = DateUtil.parse(split[0]);
                Date endTime = DateUtil.parse(split[1]);
                if (DateUtil.isIn(DateUtil.date(), startTime, endTime)) {
                    String[] deptArray = cooperateInfo.getCooperateDept().split("、");
                    TRegisterDept registerDept = registerDeptService.getById(entity.getRegisterDeptId());
                    if (StrUtil.equals(cooperateInfo.getCooperateDept(), "全部") || ArrayUtil.contains(deptArray, registerDept.getRegisterDeptName())) {
                        entity.setSourceUnitType("合作单位");
                        break;
                    }
                }
            }
        }
        // 待审批
        if (CompareUtil.compare(entity.getAuditStatus(), AuditStatusEnums.NO.getCode()) == 0) {
            long auditLevel = 0L;
            if(entity.getAuditLogVoList()!=null && !entity.getAuditLogVoList().isEmpty()){
                TAuditLogVo auditLogVoHis = entity.getAuditLogVoList().get(0);
                // 如果审批记录最新审批是退回，那么当前审批别减1
                if(auditLogVoHis.getAuditStatus()==2){
                    auditLevel = auditLogVoHis.getAuditLevel()-1<0?0:auditLogVoHis.getAuditLevel()-1;
                }
            }
            if(auditLevel==1L){
                // 设置状态为转审中
                entity.setAuditStatus(AuditStatusEnums.WAIT.getCode());
            }
            entity.setApplyTime(DateUtil.date());
            entity.setAuditLevel(auditLevel);
            entity.setGraduationAuditLevel(0L);
            entity.setNoticeStatus(0L);
            entity.setSureStatus(1L);
            entity.setAllocationStatus(0L);
            entity.setCultureStatus(0L);
            entity.setCurrentStatus(0L);
            entity.setLeaveStatus(0L);
            entity.setGraduationStatus(0L);
            entity.setGraduationStatus(0L);
            entity.setGraduationAuditStatus(0L);
            entity.setEvaluateStatus(1L);
            entity.setPayStatus(0L);
            if (ObjectUtil.isEmpty(entity.getLabelSubmit())) {
                entity.setLabelSubmit(1L);
            } else {
                entity.setLabelSubmit(entity.getLabelSubmit() + 1);
            }
            Integer countEngage = baseMapper.selectCount(Wrappers.<TRegisterInfo>lambdaQuery()
                    .ne(ObjectUtil.isNotEmpty(entity.getId()), TRegisterInfo::getId, entity.getId())
                    .eq(TRegisterInfo::getUserId, entity.getUserId())
                    .eq(TRegisterInfo::getSureStatus, SureStatusEnums.SUCCESS.getCode()));
            if (CompareUtil.compare(countEngage, 0) > 0) {
                countEngage++;
            } else {
                countEngage = 1;
            }
            entity.setLabelEngage(Long.valueOf(countEngage));
        }
        //查看是否有暂存数据
        // 同一科室同一批次只能报一次
        List<TRegisterInfo> registerInfoList = baseMapper.selectList(Wrappers.<TRegisterInfo>lambdaQuery()
                .eq(TRegisterInfo::getRegisterYear, entity.getRegisterYear())
                .eq(TRegisterInfo::getUserId, entity.getUserId())
                .eq(TRegisterInfo::getRegisterDeptId, entity.getRegisterDeptId())
                .eq(TRegisterInfo::getBatchName, entity.getBatchName())
                .eq(TRegisterInfo::getDeleteStatus,1)
                .eq(TRegisterInfo::getAuditStatus, AuditStatusEnums.SAVE.getCode())
        );
        if (ObjectUtil.isNotNull(entity.getId()) || (registerInfoList != null && !registerInfoList.isEmpty())) {
            if (registerInfoList != null && !registerInfoList.isEmpty()){
                entity.setId(registerInfoList.get(0).getId());
            }
            // 如果提交的是暂存状态，那么原来的审批状态不变
            if (CompareUtil.compare(curAuditStatus, AuditStatusEnums.SAVE.getCode()) == 0){
                TRegisterInfoVo tRegisterInfoVo = baseMapper.queryById(entity.getId());
                if(tRegisterInfoVo!=null){
                    entity.setAuditStatus(tRegisterInfoVo.getAuditStatus());
                }
            }
            baseMapper.updateById(entity);
            //删除工作经历，学习经历、语言能力
            QueryWrapper<TRegisterLearn> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("register_id",entity.getId());
            registerLearnService.remove(queryWrapper);
            QueryWrapper<TRegisterWork> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("register_id",entity.getId());
            registerWorkService.remove(queryWrapper1);
            QueryWrapper<TRegisterLanguage> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("register_id",entity.getId());
            registerLanguageService.remove(queryWrapper2);
        } else {
            baseMapper.insert(entity);
        }
        handleDetail(entity);

        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        List<String> roleList = new ArrayList<>();
        if(loginUser.getRoles()!=null){
            for (SysRole role : loginUser.getRoles()) {
                roleList.add(role.getRoleName());
            }
        }
        String optDesc = "提交申请资料";
        if (CompareUtil.compare(curAuditStatus, AuditStatusEnums.SAVE.getCode()) == 0){
            optDesc = "暂存申请信息";
        }
        TUserOptLog tUserOptLog = new TUserOptLog()
                .setOptDesc(optDesc)
                .setOptTime(entity.getUpdateTime())
                .setFromUserid(loginUser.getUserId().toString())
                .setFromUsername(loginUser.getNickName())
                .setFromRolename(StringUtils.join(roleList,","))
                .setToUserid(entity.getId().toString())
                .setToUsername(entity.getUserName());
        tUserOptLogService.save(tUserOptLog);
        return AjaxResult.success("保存成功", entity.getId());
    }

    private void checkRegister(TRegisterInfoVo entity) {
        // 同一科室同一批次只能报一次
//        Integer count = baseMapper.selectCount(Wrappers.<TRegisterInfo>lambdaQuery()
//                .eq(TRegisterInfo::getRegisterYear, entity.getRegisterYear())
//                .eq(TRegisterInfo::getUserId, entity.getUserId())
//                .eq(TRegisterInfo::getRegisterDeptId, entity.getRegisterDeptId())
//                .eq(TRegisterInfo::getBatchName, entity.getBatchName())
//                .notIn(TRegisterInfo::getAuditStatus, AuditStatusEnums.SAVE.getCode(),
//                        AuditStatusEnums.RETURNED.getCode())
//        );
//        if (CompareUtil.compare(count, 0) > 0) {
//            throw new ServiceException("您已经存在报名信息，同一科室同一批次只能报一次", 1000);
//        }
        // 同一个身份证同一时间只能有一次进修报名
//        count = baseMapper.selectCount(Wrappers.<TRegisterInfo>lambdaQuery()
//                .eq(TRegisterInfo::getIdCard, entity.getIdCard())
//                .in(TRegisterInfo::getAuditStatus,AuditStatusEnums.NO.getCode(),AuditStatusEnums.WAIT.getCode(),AuditStatusEnums.SUCCESS.getCode())
//                .and( wa->wa.between(TRegisterInfo::getDurationStartDate,entity.getDurationStartDate(),entity.getDurationEndDate())
//                                        .or()
//                        .between(TRegisterInfo::getDurationEndDate,entity.getDurationStartDate(),entity.getDurationEndDate())
//                ));
//        if (CompareUtil.compare(count, 0) > 0) {
//            throw new ServiceException("当前时间段已有报名，同一时间段无法多次报名", 1000);
//        }
        // 同一时间段只能报一个批次，两种格式，年月、年月日
//        count = baseMapper.selectCount(Wrappers.<TRegisterInfo>lambdaQuery()
//                .eq(TRegisterInfo::getRegisterYear, entity.getRegisterYear())
//                .eq(TRegisterInfo::getUserId, entity.getUserId())
//                .ne(TRegisterInfo::getBatchName, entity.getBatchName())
//                .ge(TRegisterInfo::getDurationStartDate, entity.getDurationStartDate())
//                .lt(TRegisterInfo::getDurationEndDate, entity.getDurationEndDate()));
//        if (CompareUtil.compare(count, 0) > 0) {
//            throw new ServiceException("您已经存在报名信息，同一时间段内只能报一个批次", 1000);
//        }
        // 审核中，不能报名其他的
//        count = baseMapper.selectCount(Wrappers.<TRegisterInfo>lambdaQuery()
//                .eq(TRegisterInfo::getRegisterYear, entity.getRegisterYear())
//                .eq(TRegisterInfo::getUserId, entity.getUserId())
//                .in(TRegisterInfo::getAuditStatus, Arrays.asList(AuditStatusEnums.NO.getCode(), AuditStatusEnums.WAIT.getCode())));
//        if (CompareUtil.compare(count, 0) > 0) {
//            throw new ServiceException("您有报名信息正在审核中，预计审核时间15个工作日，请在审核完成后，再确认是否报名！", 1000);
//        }
        // 审批拒绝后，同一批次的这个科室无法报名，但是其他批次
//        Integer isFail = baseMapper.selectCount(Wrappers.<TRegisterInfo>lambdaQuery()
//                .eq(TRegisterInfo::getUserId, entity.getUserId())
//                .eq(TRegisterInfo::getRegisterDeptId, entity.getRegisterDeptId())
//                .eq(TRegisterInfo::getRegisterYear, entity.getRegisterYear())
//                .eq(TRegisterInfo::getBatchName, entity.getBatchName())
//                .eq(TRegisterInfo::getAuditStatus, AuditStatusEnums.FAIL.getCode()));
//        if (CompareUtil.compare(isFail, 0) > 0) {
//            throw new ServiceException("您的申请信息已经被驳回，无法报名", 1000);
//        }
    }

    private void handleDetail(TRegisterInfoVo entity) {
        if (CollUtil.isNotEmpty(entity.getRegisterLearnVoList())) {
            entity.getRegisterLearnVoList().forEach(e -> e.setRegisterId(entity.getId()));
            registerLearnService.saveOrUpdateBatch(BeanUtil.copyToList(entity.getRegisterLearnVoList(), TRegisterLearn.class));
        }
        if (CollUtil.isNotEmpty(entity.getRegisterWorkVoList())) {
            entity.getRegisterWorkVoList().forEach(e -> e.setRegisterId(entity.getId()));
            registerWorkService.saveOrUpdateBatch(BeanUtil.copyToList(entity.getRegisterWorkVoList(), TRegisterWork.class));
        }
        if (CollUtil.isNotEmpty(entity.getRegisterLanguageVoList())) {
            entity.getRegisterLanguageVoList().forEach(e -> e.setRegisterId(entity.getId()));
            registerLanguageService.saveOrUpdateBatch(BeanUtil.copyToList(entity.getRegisterLanguageVoList(), TRegisterLanguage.class));
        }
    }

    @Override
    public AjaxResult getLast() {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        TRegisterInfo registerInfo = this.getOne(Wrappers.<TRegisterInfo>lambdaQuery()
                .eq(TRegisterInfo::getUserId, userId)
                .eq(TRegisterInfo::getNoticeStatus, NoticeStatusEnums.SUCCESS.getCode())
                .orderByDesc(TRegisterInfo::getId)
                .last("limit 1"));
        return AjaxResult.success("查询成功", registerInfo);
    }

    @Override
    public List<ExportRegisterInfoVo> getExportList(TRegisterInfoVo entity) {
        handleAuthRegister(entity);
        return baseMapper.getExportList(entity);
    }

    @Override
    public List<RegisterManualInfoVo> exportRegisterInfo(TRegisterInfoVo entity) {
        handleAuthRegister(entity);
        return baseMapper.exportRegisterInfo(entity);
    }

    @Override
    public List<RegisterManualAllInfoVo> exportRegisterInfoAll(TRegisterInfoVo entity) {
        handleAuthRegister(entity);
        return baseMapper.exportRegisterInfoAll(entity);
    }

    @Override
    public void updateCultureStatusForNoCulture() {
        baseMapper.updateCultureStatusForNoCulture();
    }

    @Override
    public void insertCultureStatusForNoCultureLog() {
        baseMapper.insertCultureStatusForNoCultureLog();
    }

    @Override
    public List<ExportSignedFilesVo> exportAllSignedFiles(TRegisterInfoVo entity) {
        handleAuthRegister(entity);
        return baseMapper.exportAllSignedFiles(entity);
    }

    @Override
    public TableDataInfo<TRegisterXXQYVo> getXXQYRegisterList(OpenApiTokenVo tokenVo) {
        Page<TRegisterXXQYVo> page = baseMapper.getXXQYRegisterList(new Page<>(tokenVo.getPageNum(),tokenVo.getPageSize()));
        return PageUtils.buildDataInfo(page);
    }

    @Override
    public TableDataInfo<TRegisterXXQYVo> getXxqyJyRegisterList(OpenApiTokenVo tokenVo) {
        Page<TRegisterXXQYVo> page = this.baseMapper.getXxqyJyRegisterList(new Page<>(tokenVo.getPageNum(),tokenVo.getPageSize()));
        return PageUtils.buildDataInfo(page);
    }

    @Override
    public AjaxResult judgeRegister(Long id) {
        TRegisterInfo registerInfo = getById(id);
        if (registerInfo.getAgentUserId() == null) { //不是代理报名
            String batchDate = registerInfo.getBatchDate();
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            try {
                String fh= batchDate.contains("-")?"-":"~";
                String[] split = batchDate.split(fh);
                Date endDate = format.parse(split[1]);
                // 如果是退回状态，结束日期加30天
                if (AuditStatusEnums.RETURNED.getCode().equals(registerInfo.getAuditStatus())) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(endDate);
                    calendar.add(Calendar.DAY_OF_MONTH, 30); // 增加30天
                    endDate = calendar.getTime();
                }
                Date date = new Date();
                int compare = DateUtil.compare(date, endDate);
                if (compare >= 1) {
                    return AjaxResult.error("当前进修期限已过，请删除后重新提交进行申请");
                }
            } catch (ParseException e) {
                log.error("进修开始时间格式解析异常,进行编号ID:" + id);
            }
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public Boolean batchRemoveByIds(List<Long> registerIds) {
        // 删除进修主表
        boolean result = this.removeByIds(registerIds);
        // 删除分配的带教老师
        registerAllocationService.update(getDelStatusUpdateWrapper(registerIds));
        // 删除语言信息
        registerLanguageService.update(getDelStatusUpdateWrapper(registerIds));
        // 删除学习经历
        registerLearnService.update(getDelStatusUpdateWrapper(registerIds));
        // 删除考勤
        registerLeaveService.update(getDelStatusUpdateWrapper(registerIds));
        // 删除记录手册
        registerManualService.update(getDelStatusUpdateWrapper(registerIds));
        // 删除进修通知
        registerNoticeService.update(getDelStatusUpdateWrapper(registerIds));
        // 删除支付订单
        tRegisterPaymentOrderService.update(getDelStatusUpdateWrapper(registerIds));
        // 删除签名
        registerSignService.update(getDelStatusUpdateWrapper(registerIds));
        // 删除工作经历
        registerWorkService.update(getDelStatusUpdateWrapper(registerIds));
        return result;
    }

    private <T> UpdateWrapper<T> getDelStatusUpdateWrapper(List<Long> registerIds) {
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("register_id", registerIds);
        // 状态2为删除
        updateWrapper.set("delete_status", 2L);
        return updateWrapper;
    }

}
